package org.platon.template.rpa;

import ai.platon.pulsar.common.options.LoadOptions;
import ai.platon.pulsar.context.PulsarContexts;
import ai.platon.pulsar.crawl.event.WebPageJvmWebDriverEventHandler;
import ai.platon.pulsar.crawl.fetch.driver.JvmWebDriver;
import ai.platon.pulsar.persist.WebPage;
import ai.platon.pulsar.session.PulsarSession;
import kotlin.coroutines.Continuation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class RPACrawler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());  // 创建Logger对象

    private final PulsarSession session;  // 声明PulsarSession对象

    public final Map<String, String> fieldSelectors;  // 声明Map对象，存储选择器

    public RPACrawler() {  // 无参构造方法
        this(PulsarContexts.createSession());  // 调用含参构造方法
    }

    public RPACrawler(PulsarSession session) {  // 含参构造方法
        this.session = session;  // 初始化session

        fieldSelectors = new HashMap<>(Map.of(  // 初始化fieldSelectors
                "sku-name", ".sku-name",
                "news", ".news",
                "summary", ".summary"
        ));
    }

    public LoadOptions options(String args) {  // 定义options方法，返回LoadOptions对象
        var options = session.options(args, null);  // 初始化options对象
        var be = options.getEvent().getBrowseEvent();  // 获取BrowseEvent对象

        // 设置OnWillComputeFeature方法
        be.getOnWillComputeFeature().addLast(new WebPageJvmWebDriverEventHandler() {
            @Override
            public Object invoke(WebPage page, JvmWebDriver driver, Continuation<? super Object> continuation) {
                fieldSelectors.values().forEach(selector -> interact(selector, driver));  // 调用interact方法
                return null;
            }
        });

        // 设置OnFeatureComputed方法
        be.getOnFeatureComputed().addLast(new WebPageJvmWebDriverEventHandler() {
            @Override
            public Object invoke(WebPage page, JvmWebDriver driver, Continuation<? super Object> $completion) {
                logger.info("Feature computed");  // 打印日志信息
                return null;
            }
        });

        return options;  // 返回options对象
    }

    private void interact(String selector, JvmWebDriver driver) {  // 定义私有方法interact
        var delayedExecutor = CompletableFuture.delayedExecutor(2, TimeUnit.SECONDS);  // 初始化延迟执行器
        var searchBoxSelector = ".form input[type=text]";  // 初始化搜索框选择器

        // 判断元素是否存在
        driver.existsAsync(selector).thenAccept(exists -> {
            if (exists) {
                driver.clickAsync(selector)  // 点击元素
                        .thenCompose(ignored -> driver.firstTextAsync(selector))  // 获取元素文本
                        .thenAcceptAsync(text -> driver.typeAsync(searchBoxSelector, text.substring(1, 4)), delayedExecutor)  // 在搜索框中输入文本
                        .thenRun(() -> { logger.info("{} clicked", selector); })  // 打印日志信息
                        .join();
            }
        }).join();
    }

    public static void main(String[] argv) {  // 定义main方法
        var url = "https://item.jd.com/10023632209832.html";  // 定义URL
        var args = "-refresh -parse ";  // 定义参数
        var session = PulsarContexts.createSession();  // 创建PulsarSession对象
        var crawler = new RPACrawler(session);  // 创建RPACrawler对象
        var fields = session.scrape(url, crawler.options(args), crawler.fieldSelectors);  // 爬取URL内容
        System.out.println(fields);  // 打印结果
    }
}